package qscript;

import org.qscript.Argument;
import org.qscript.Script;
import org.qscript.Solver$;
import org.qscript.events.HaltExecutionEvent;
import org.qscript.events.ScriptEvent;
import org.qscript.eventsonfire.EventHandler;
import org.qscript.operator.Operator;
import org.qscript.operator.OperatorSet;

import processing.core.PApplet;

public class HypotenuseExample extends PApplet {
	Script script;
	float a = 1, b = 1, h = 1;
	String stopText = "";

	public void setup() {
	  size(400, 400);
	  HypotenuseFunction h = new HypotenuseFunction("hypot", 2, 30, Operator.FUNCTION);
	  OperatorSet.get().addOperator(h);

	  String[] code = {
	    "WHILE(true)", 
	    "  a = rnd(10, 100)", 
	    "  b = rnd(10, 100)", 
	    "  h = hypot(a, b)", 
	    "  WAIT(rnd(3000, 6000))", 
	    "WEND"
	  };

	  script = new Script(code);
	  // Script events are to be sent to this object
	  script.addListener(this);

	  Solver$.evaluate(script);
	}

	public void keyTyped() {
	  if (key == 's' || key == 'S')
	    script.stop();
	}

	public void draw() {
	  background(200, 255, 200);
	  drawTriangle(a, b, h);
	  fill(0);
	  if (!script.isStopped())
	    text("Working ...", 20, 20);
	  else
	    text(stopText, 20, 20);
	}

	@EventHandler
	public void onScriptEvent(ScriptEvent event) {
	  if (event instanceof HpotCalculatedEvent) {
	    a = script.getVariable("a").toFloat();
	    b = script.getVariable("b").toFloat();
	    h = ((Argument)event.extra[0]).toFloat();
	  }
	  else if (event instanceof HaltExecutionEvent) {
	    stopText = "Program halted";
	  }
	}

	public void mouseClicked(){
	  save("triangle" + millis()%100 + ".png");
	}

	public void drawTriangle(float a, float b,float h) {
	  float s = (400 - 80.0f)/ max(a, b);
	  float ap = a*s;
	  float bp = b*s;

	  stroke(0);
	  strokeWeight(1.5f);
	  fill(0, 128, 0);
	  pushMatrix();
	  translate(width-40, height - 40);
	  beginShape(TRIANGLES);
	  vertex(0, 0);
	  vertex(-ap, 0);
	  vertex(0, -bp);
	  endShape();
	  // a length
	  pushMatrix();
	  translate(-ap/2.5f, 14);
	  text(""+a, -textWidth(""+a)/2, 0);
	  popMatrix();
	  // b length
	  pushMatrix();
	  translate(6, -bp/2.5f);
	  rotate(HALF_PI);
	  text(""+b, -textWidth(""+b)/2, 0);
	  popMatrix();
	  // h length
	  pushMatrix();
	  translate(-6-ap/2, -6-bp/2);
	  rotate(-atan2(b, a));
	  text(""+h, -textWidth(""+h)/2, 0);
	  popMatrix();
	  popMatrix();
	}

}
